import styles from './index.module.scss'
import {
  Card,
  Breadcrumb,
  Form,
  Input,
  Button,
  Space,
  Radio,
  Upload,
  message,
  Modal
} from 'antd'
import { Link, useHistory, useParams } from 'react-router-dom'
import { useState, useRef, useEffect } from 'react'
import Channel from '@/components/Channel'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { PlusSquareOutlined } from '@ant-design/icons'
import { useDispatch } from 'react-redux'
import { postArt, getArt, putArt } from '@/store/actions/login.js'
function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}

export default function Publish () {
  const [fileList, setFileList] = useState([])
  const [type, setType] = useState(1)
  const history = useHistory()
  const refList = useRef(fileList)
  const refFrom = useRef(null)
  const dispatch = useDispatch()
  const { id } = useParams()
  const handleChange = ({ fileList }) => {
    // console.log(fileList)
    setFileList(fileList)
    refList.current = fileList
    refFrom.current.validateFields(['type'])
  }
  const changeType = (e) => {
    setType(e.target.value)
    setFileList(refList.current.slice(0, e.target.value))
  }
  const setFromDate = async ({ type, ...res }, draft = false) => {
    const data = {
      ...res,
      cover: {
        type,
        images: fileList.map((item) => item.url || item.response.data.url)
      }
    }
    try {
      if (id) {
        await dispatch(putArt(data, draft, id))
      } else {
        await dispatch(postArt(data, draft))
      }
      const msg = id ? '编辑成功' : '添加成功'
      message.success(msg, 0.5, () => {
        history.push('/home/article')
      })
    } catch (error) {
      message.error(error.response.message, 0.5)
    }
  }
  const submit = (val) => {
    setFromDate(val)
  }
  const saveDraft = async () => {
    const val = await refFrom.current.validateFields()
    setFromDate(val, true)
  }
  useEffect(
    () => {
      const getArtInfo = async (id) => {
        const {
          data: { channel_id: channel, content, cover, title }
        } = await dispatch(getArt(id))
        const art = {
          title,
          channel_id: channel,
          content,
          type: cover.type
        }
        refFrom.current.setFieldsValue(art)
        const tFileList = cover.images.map((item) => ({ url: item }))
        setFileList(tFileList)
        // eslint-disable-next-line no-debugger
        // debugger
        refList.current = tFileList
        // console.log('.....', refList, fileList)
        setType(cover.type)
      }
      if (!id) return
      getArtInfo(id)
    },
    [id]
  )
  // console.log('.....', refList, fileList)
  // 预览
  const [previewVisible, setPreviewVisible] = useState(false)
  const [previewImage, setPreviewImage] = useState('')
  const handlePreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj)
    }
    setPreviewImage(file.url || file.preview)
    setPreviewVisible(true)
    // this.setState({
    //   previewImage: file.url || file.preview,
    //   previewVisible: true,
    //   previewTitle:
    //     file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
    // })
  }
  const handleCancel = () => {
    setPreviewVisible(false)
  }
  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>{id ? '编辑' : '发布'}文章</Breadcrumb.Item>
          </Breadcrumb>
        }>
        <Form
          ref={refFrom}
          onFinish={submit}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          size="large"
          initialValues={{ content: '请输入文章内容', type: 1 }}>
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '必填' }]}>
            <Input placeholder="请输入文章的标题" style={{ width: 400 }} />
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '必填' }]}>
            <Channel />
          </Form.Item>
          <Form.Item
            label="封面"
            name="type"
            rules={[
              {
                validator (rule, val) {
                  if (fileList.length === val) return Promise.resolve()
                  return Promise.reject(new Error('与上传数量不一致'))
                }
              }
            ]}>
            <Radio.Group value={type} onChange={changeType}>
              <Radio value={1}>1图</Radio>
              <Radio value={3}>3图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item>
            <Upload
              name="image"
              listType="picture-card"
              className="avatar-uploader"
              action="http://geek.itheima.net/v1_0/upload"
              fileList={fileList}
              onPreview={handlePreview}
              onChange={handleChange}>
              {fileList.length < type && <PlusSquareOutlined />}
            </Upload>
          </Form.Item>
          <Modal
            visible={previewVisible}
            title="预览"
            footer={null}
            onCancel={handleCancel}>
            <img alt="example" style={{ width: '100%' }} src={previewImage} />
          </Modal>
          <Form.Item label="内容" name="content">
            <ReactQuill />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                发布文章
              </Button>
              <Button onClick={saveDraft}>存入草稿</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
